<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html class="win-frame">
<head>
<title>${name_china}管理-新建${name_china}</title>
 <%@include file="/common/head.jsp" %>
<style>
.maskback{
	position:fixed;
	width:100%;
	height:100%;
	top:0px;
	background:rgba(0,0,0,0.7);
}
.mainback{
    width: 40%;
    height: 600px;
    background: #fff;
    margin: 0 auto;
    margin-top: 4%;
    overflow: auto;
}
#funcbar{
    margin-top: 58px;
    margin-bottom: 16px;

}
</style>
</head>
<body class="iframe-page">
<div class="page-title-wrapper">
    <div class="page-title">
        <div class="page-title-text">
            <span>${name_china}管理</span>
            <span class="split"></span>
            <span>新建${name_china}</span>
        </div>
        <a id="goBack" class="btn-return distance-left" href="javascript:;"><i class="icon icon-arrow-left"></i>返回上级</a>
    </div>
    <div class="page-title-border"></div>
</div>

<form id="addForm" method="post">
  <div id="left" style="width:80%;float:left">
	 <div class="form-wrapper">    
	      <div class="form-cont">
	        <p class="form-cont-title">平台</p> 
	        <input type="hidden" id="specialId" name="specialId"> 
	        <input type="hidden" name="spuIds" id="spuIds"/> 
	        <input type="text" id="spuPlatform" name="spuPlatform" class="summer-input summer-validatebox"  data-validatebox="validType:['maxLength[20]']"/> 
	     </div>
	     
	     <div class="form-cont">
	        <p class="form-cont-title">开始时间</p>
	        <input type="text" id="starttime" name="starttime" class="summer-input summer-validatebox"  data-validatebox="validType:['maxLength[20]']"/> 
	     </div>
	     
	     <div class="form-cont">
	        <p class="form-cont-title">结束时间</p>
	        <input type="text" id="endtime" name="endtime" class="summer-input summer-validatebox"  data-validatebox="validType:['maxLength[20]']"/> 
	     </div>
	       
	 <div class="form-btn-wrapper" id="funcbar">
        <a class="btn btn-normal" id="backBtn">关闭</a>
    </div>
    <div class="form-cont" id="spu">
    <input type="hidden" name="delSpuIds" id="delSpuIds"/>
  	</div> 
  </div>

  </div>

</form>


<div class="search-field" >
	<span class="field-cont">
        <span class="field-cont-title">商品名称</span>
        <input type="text" class="summer-input" id="goodsName"/>
    </span>
    
     <span class="field-cont">
        <span class="field-cont-title">商品分类</span>
        <input type="text" id="categoryId" name="categoryId" class="summer-input summer-validatebox"  data-validatebox="validType:['required','maxLength[500]']"/> 
    </span><br/>
   
     <span class="field-cont">
        <span class="field-cont-title">是否爆款</span>
        <input type="text" class="summer-input" id="isHot"/>
    </span><br/>
    <span class="field-btn-wrapper">
        <a id="search" class="btn btn-primary btn-icon wave distance-right"><i class="icon icon-search"></i></a>
        <a id="reset" class="btn btn-icon wave wave-dark"><i class="icon icon-refresh"></i></a>
        <a id="setSpecial" class="btn btn-primary  wave distance-right">设置为特卖商品</a>
    </span>
</div>
 <!-- <div class="form-cont" id="goodsList">
 </div>	 -->
<div id="t-wrap">
    <table class="summer-datagrid" id="dataList">
	    <col width="10%">
	    <col width="10%">
	    <col width="30%">
	    <col width="20%">
	    <col width="20%">
	    <col width="20%">
	    <col width="20%">
	    <col width="25%">
	    <thead>
		     <tr>
		    <th><div class="summer-datagrid-cell"></div></th>
		    <th><div class="summer-datagrid-cell">排序</div></th>
		    <th><div class="summer-datagrid-cell">名称</div></th>
		    <th><div class="summer-datagrid-cell">图片</div></th>
		    <th><div class="summer-datagrid-cell">类型</div></th>
		    <th><div class="summer-datagrid-cell">分类</div></th>
		    <th><div class="summer-datagrid-cell">价钱（原价、券后价、佣金数）</div></th>
		    <th><div class="summer-datagrid-cell">时间</div></th>
			 </tr>
	    </thead>
    </table>
    
</div>
<form id="editForm">
<div style="display: none" class="maskback">
<input type="text" id="goods" name="goods">
     <div class="mainback">
     <div id="goodsList">
     </div>
	     <div class="form-btn-wrapper" id="funcbar" style="margin-top: 100px;">
	        <a id="save" href="javascript:;" class="btn btn-ok btn-normal  wave distance-right" >保存</a>
	        <a class="btn btn-normal" id="backBtnMark">关闭</a>
	        
	     </div>
     </div>
</div>
</form>
     

<script>
    var  mData,
    	 editData,
    	 goodsID = "",
    	 goodsData,
    	 permission = CommonUtil.getPermission('${name_english}');
    $(function () {
    	editData = ${editData};
    	goodsData = ${goodsData};
    	mData = ${mData};
    	//初始化funcbar
     	$('#funcbar').prepend($.funcbar({
            type: 'button',
            data: permission,
            permit: ['${name_english}:add']
        }));
    	
     	if(goodsData != "no"){
    		var Gdata = "";
    		for(var k=0;k<goodsData.length;k++){
    			Gdata = Gdata + '<div style="float:left;width:20%;">'
 				   +'<input type="hidden" id="spuId'+k+'" value="'+goodsData[k].id+'">'
 				   +'<div style="width:148px;height:148px"><img style="width:100%;height:100%;" src="'+goodsData[k].mainImageUrl+'"></div>'
 				   +'<div style="width:90%;height:100px;"><p>'+goodsData[k].goodsName+'</p></div>'
 				   +'<input type="checkbox" id="spuID'+k+'" name="spuID'+k+'" value="'+goodsData[k].id+'">'
 				   +'</div>';
    			goodsID = goodsID +","+ goodsData[k].id;//将已设置展示的商品ID编号累计
    		}
    		$("#spu").append(Gdata);
    		//商品编号列表
    		$("#spuIds").val(goodsID);
    	}
     	//保存按钮
    	$('#funcbar').on('click', 'a[data-permit="${name_english}:add"]', submitAdd);
     	$('#search').on('click', reloadTable);
     	$('#reset').on('click', function() {
			//重置文本框的值
			$('#goodsName').val('');
			$('#spuPlatform').combobox('clear');
			$('#categoryId').combobox('clear');
			$('#isHot').combobox('clear');
			reloadTable();
		});
     
     if(mData != "no"){
    	 $("#price").val(mData.price);
    	 $("#conPrice").val(mData.conPrice);
     }
     //是否展示商品编辑
     var spuPlatform = $("#spuPlatform").val();
  	 if(spuPlatform != "yh"){
  		$("#isShow").css("display","none");
  	 }
  	 //设置特卖
  	 //弹窗
     $('#setSpecial').on('click', function() {
    	var spuId = $("input[name='spuId']:checked").serialize(),
    	spuIds = $("#spuIds").val();
     	window.location.href = CONST_URL.SET_SPECIAL+"?spuId="+spuId+"&spuIds="+spuIds
     });
   
     //弹窗
     $('#t-wrap').on('click', 'a[data-permit="${name_english}:addGoods"]', function() {
     	var $this = $(this),
     	    id = $this.closest('tr').find('td[data-field="id"]').attr('data-value');
     	console.log(id);
     	$("#spuId").val(id);
     	window.location.href = CONST_URL.ADD_GOODS+"?spuId="+id+"&specialId="+specialId;
     	$(".maskback").show();     	
     });
     $("#backBtnMark").click(function(){
 		$(".maskback").hide();
     	window.location.href = CONST_URL.INIT_ADD; 	
 	});
     
     //编辑商品保存
     $("#save").on('click',submit);
   //弹窗
     
     //初始化下拉选项
   	  $('#spuPlatform').combobox({
             valueField : 'code',
             textField : 'name',
             url : COMMON_URL.getCode + '?type=T_DM_T_GOODS_SPU_SPU_PLATFORM'
         });
    	 $('#isHot').combobox({
             valueField : 'code',
             textField : 'name',
             url : COMMON_URL.getCode + '?type=T_DM_T_GOODS_SPU_IS_HOT'
         });
    	//初始化下拉选项  商品所属公司
    	 $('#categoryId').combobox({
             url : CONST_URL.GET_GOODS_CATEGORY, 
             valueField : 'id',
             async:false,
             textField : 'name'
         });
    	
    	//初始化下拉选项  商品所属公司
    	 $('#starttime').combobox({
             url : CONST_URL.GET_TIME, 
             valueField : 'startTime',
             async:false,
             textField : 'startTime'
         }); 
    	 $('#endtime').combobox({
             url : CONST_URL.GET_TIME, 
             valueField : 'endTime',
             async:false,
             textField : 'endTime'
         }); 
    	//返回按钮
    	$('#backBtn,#goBack').on('click',backMain);
    	createTable();
    });
    //表单提交
     //表单提交
    function submit(event) {
    	var goods = "";
    	$('#goodsList div').each(function(i){
    		var param1 = $("div input[name='spuId"+i+"']").val(); 
    		var param2 = $("div input[name='couponMoney"+i+"']").val();
    		var param3 = $("div input[name='maxCount"+i+"']").val();
    		var param4 = $("div input[name='wlCommission"+i+"']").val();
    		if(typeof(param1) == "undefined"){
    			return false;
    		}else{
        		goods += "spuId="+param1 +","+ "couponMoney="+param2 +","+ "maxCount="+param3 +","+ "wlCommission="+param4 +"#";
    		}
    		});
    	$("#goods").val(goods);
    	 $("#editForm").form({
             ajax: {
                 url: CONST_URL.ADD_EDIT_GOODS,
                  data:{
        				"goods" :$("#goods").val()
        			 }  
             },
             onSubmitSuccess: function (data) {
            	 console.log(data);
            	 if(data.msg != "null"){
            		 alert(data.msg);
            	 }else{
            		 $.stip({
       	                type:'ok',//显示类型 有info、 ok、 danger
       	                text: '保存成功！',
       	                onBeforeHide: function () {
                        	 
       	               }
                   	});
            		//隐藏蒙版
                		$(".maskback").hide();
                  	 //刷新商品列表
                		reloadTable();
            	 }
              }
         }).form("submit");
    }
    //新增特卖保存
    //表单提交
    function submitAdd() {
    	//var spuId = $("input[name='spuId']:checked").serialize();
    	var spuPlatform = $('#spuPlatform').combobox('getValue');
    	if(spuPlatform == ""){
    		alert("请选择平台并查询！");
    	}else{
    		//$("#spuIds").val(spuId);
        	var goodsIds = $("#spuIds").val();
        	if(goodsIds == ""){
        		alert("请选择特卖商品！");
        	}else{
        		$("#addForm").form({
                 	 buttons : ['#saveBtn','#saveBtnContinue'],
                      ajax: {
                          url: CONST_URL.ADD,
                          data:{
                       	   "goodsIds":  goodsIds,
                       	 	"starttime":$('#starttime').combobox('getValue'),
           					"endtime":$('#endtime').combobox('getValue'),
           					"spuPlatform":$('#spuPlatform').combobox('getValue')
              			 }
                      },
                      onSubmitSuccess: function (data) {
                   	     //所选商品与平台相同，可继续完成新建特卖活动，否则不允许
                   	     console.log(data);
                    	 if(data.msg == "null"){
                   		 $.stip({
            	                type:'ok',//显示类型 有info、 ok、 danger
            	                text: '保存成功！',
            	                onBeforeHide: function () {
            	                	reloadTable(); 
            	               }
                        	});

                    		var html = "";
                      	 $("#goodsList").val("");
                      	for(var i=0;i<data.data.length;i++){
                      		console.log(data.data[i]);
                      		html = html
                      			  +'<hr height:2px noshade=true/>'
                      			  +'<div class="form-cont" style="top:40px;">'
                   	     	  +'<p class="form-cont-title">商品名称</p>'
                   	          +'<input type="text" id="goodsName'+i+'" name="goodsName'+i+'" value="'+data.data[i].goodsName+'" class="summer-input summer-validatebox" disabled/> '
                   	          +'</div>'
                   	          +'<div class="form-cont" style="top:40px;">'
                   	     	  +'<p class="form-cont-title">商品图片</p>'
                   	     	  +'<img src="'+data.data[i].mainImageUrl+'" height="100px" width="100px">'
                   	          +'<input type="hidden" id="mainImageUrl'+i+'" name="mainImageUrl'+i+'" value="'+data.data[i].mainImageUrl+'" class="summer-input summer-validatebox" disabled/> '
                   	          +'</div>'
                      			  + '<div class="form-cont" style="top:40px;">'
                      			  +'<input type="hidden" name="spuId'+i+'" id="spuId'+i+'" value="'+data.data[i].id+'"/>'
                    	    	  +'<p class="form-cont-title">商品原价</p>'
                   	          +'<input type="text" id="price'+i+'" name="price'+i+'" value="'+data.data[i].price+'" class="summer-input summer-validatebox" disabled/> '
                   	          +'</div>'
                   	     	  +'<div class="form-cont" style="top:40px;">'
                   	     	  +'<p class="form-cont-title">券后价</p>'
                   	          +'<input type="text" id="conPrice'+i+'" name="conPrice'+i+'" value="'+data.data[i].conPrice+'" class="summer-input summer-validatebox" disabled/> '
                   	          +'</div>'
                   	     	  +'<div id="isShow">'
                   	     	  +'<div class="form-cont" style="top:40px;">'
                        	 	  +'<p class="form-cont-title"><span class="field-required">*</span>红包券金额</p>'
                   	          +'<input type="text" id="couponMoney'+i+'" name="couponMoney'+i+'" class="summer-input summer-validatebox" />'
                   	          +'</div>'
                   	     	  +'<div class="form-cont" style="top:40px;">'
                   	     	  +'<p class="form-cont-title"><span class="field-required">*</span>数量</p>'
                   	          +'<input type="text" id="maxCount'+i+'" name="maxCount'+i+'" class="summer-input summer-validatebox" />'
                   	          +'</div>'
                   	     	  +'<div class="form-cont" style="top:40px;">'
                   	     	  +'<p class="form-cont-title"><span class="field-required">*</span>佣金</p>'
                   	          +'<input type="text" id="wlCommission'+i+'" name="wlCommission'+i+'" class="summer-input summer-validatebox" />'
                   	          +'</div>'
                   	     	  +'</div>'
                      	}
                       	$("#goodsList").append(html);
                       	$(".maskback").show();
                       	}else{
                       		alert(data.msg);
                       		}
                   	     }
                  }).form("submit");
        	}
    	}
    	
    }
 // 重新加载表格
	function reloadTable() {
		createTable();
		$('#dataList').datagrid('reload', {
			ajax : {
				param : {
					"goodsName": trimSpace($('#goodsName').val()),
					"spuPlatform":$('#spuPlatform').combobox('getValue'),
					"categoryId":$('#categoryId').combobox('getValue'),
					"isHot":$('#isHot').combobox('getValue')
				}
			}
		});
	}
	
	//创建表格
	function createTable() {
		
		$('#dataList')
				.datagrid(
						{
							ajax : {
								url : CONST_URL.GOODS_LIST,
								param : {	
									"goodsName": trimSpace($('#goodsName').val()),
									"spuPlatform":$('#spuPlatform').combobox('getValue'),
									"categoryId":$('#categoryId').combobox('getValue'),
									"isHot":$('#isHot').combobox('getValue')
								},
								success : function(data) { //成功 
									alert("Data Saved: " + msg);
								}
							},
							columns : [
									{
										field : 'spuId',
										hidden : true
									},
									{
										render : function(rowData){
											return '<input type="checkbox" id="spuId" name="spuId" value="'+rowData.spuId+'">';
										}
									},
									{
										field : 'reorder'
									},
									{
										field : 'goodsName'
									},
									{
										render : function(rowData){
											return '<img width="100" height="100" src="'+rowData.mainImageUrl+'">';
										}
									},
									{
										field : 'spuPlatform'
									},
									{
										field : 'categoryId'
									},
									{
										render : function(rowData){
											return '<p>原价：'+rowData.wlPrice+'</p><br/>'
												  +'<p>券后价：'+rowData.conPrice+'</p><br/>'
												  +'<p>佣金：'+rowData.wlCommission+'</p>';
										}
									},
									{
										field : 'createTime'
									},
									{
										render : function(rowData) {
											if(rowData.specialId != "" && rowData.spuPlatform != "yh"){
						                        return $.funcbar({
						                          data : permission, //请求的数据
						                          type : 'text', //类型
						                          display : 1, //显示数量
						                          permit : [
						                              '${name_english}:addGoods'
						                               ]
						                        //需要的权限按钮
						                        });
						                      }
										}
									}

							]
						});
	}
    
    //保存并继续清空form
    function resetForm(){
        //$('#xm,#zw,#cs,#bgdh,#sjhm').val('');
    }
    
    //返回主页面
    function backMain() {
    	window.location.href = CONST_URL.INIT_MAIN;
    }
    
   
    //请求url
    var CONST_URL = {
    	INIT_MAIN: basePath + "${common_url}init",
       	ADD: basePath + "${common_url}add",
       	GET_GOODS_CATEGORY: basePath + "${common_url}getGoodsCategory",
       	GOODS_LIST: basePath + "${common_url}goodsList",
       	DEL_SPECIAL: basePath + "${common_url}delSpecial",
       	GET_TIME: basePath + "${common_url}getTime",
       	INIT_SET: basePath + "${common_url}initSet",
       	ADD_EDIT_GOODS: basePath + "${common_url}addEditGoods",
       	ADD_GOODS: basePath + "${common_url}addGoods",
       	INIT_ADD: basePath + "${common_url}initAdd",
       	SET_SPECIAL: basePath + "${common_url}setSpecial"
    };
    
</script>
</body>
</html>